//
//  PullRefreshHeaderView.m
//  KYPullRefreshTableHeader
//
//  Created by wesleyxiao on 14-3-17.
//  Copyright (c) 2014年 wesleyxiao. All rights reserved.
//

#import "PullRefreshHeaderView.h"

#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

@interface PullRefreshHeaderView()
- (void)setState:(PullRefreshState)aState;
@end

@implementation PullRefreshHeaderView
@synthesize  delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		self.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
        
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 30.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont systemFontOfSize:12.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
        label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
        //上次更新的label
		_lastUpdatedLabel=label;
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 48.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont boldSystemFontOfSize:13.0f];
		label.textColor = TEXT_COLOR;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
        
		_statusLabel=label;
        
        //箭头layer
        CALayer *layer = [CALayer layer];
		layer.frame = CGRectMake(25.0f, frame.size.height - 65.0f, 30.0f, 55.0f);
		layer.contentsGravity = kCAGravityResizeAspect;
		layer.contents = (id)[UIImage imageNamed:@"blueArrow.png"].CGImage;
        
        [[self layer] addSublayer:layer];
		_arrowImage=layer;
		
        //菊花view
		UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
		view.frame = CGRectMake(25.0f, frame.size.height - 38.0f, 20.0f, 20.0f);
        _activityView = view;
		[self addSubview:view];
    }
    
    return self;
}

-(void)refreshLastUpdatedDate
{
    NSLog(@"向代理对象取一下上次更新的时间");
    
    if ([delegate respondsToSelector:@selector(refreshTableHeaderDataSourceLastUpdated:)])
    {
		NSDate *date = [delegate refreshTableHeaderDataSourceLastUpdated:self];
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setAMSymbol:@"AM"];
		[formatter setPMSymbol:@"PM"];
		[formatter setDateFormat:@"MM/dd/yyyy hh:mm:a"];
		_lastUpdatedLabel.text = [NSString stringWithFormat:@"Last Updated: %@", [formatter stringFromDate:date]];
		[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"RefreshTableView_LastRefresh"];
		[[NSUserDefaults standardUserDefaults] synchronize];
		
	}
    else {
    
    _lastUpdatedLabel.text = nil;
    
	}
    
}
- (void)refreshScrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"scrollview 被拉");
    
    //如果是loding状态，显示下拉view
	if (_state == PullRefreshLoading) {
		
		CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
		offset = MIN(offset, 60);
		scrollView.contentInset = UIEdgeInsetsMake(offset, 0.0f, 0.0f, 0.0f);
		
	}
    else if (scrollView.isDragging) {
		
		BOOL _loading = NO;
        //1
		if ([delegate respondsToSelector:@selector(refreshTableHeaderDataSourceIsLoading:)])
        {
			_loading = [delegate refreshTableHeaderDataSourceIsLoading:self];
		}
		
		if (_state == PullRefreshPulling && scrollView.contentOffset.y > -65.0f && scrollView.contentOffset.y < 0.0f && !_loading) {
			[self setState:PullRefreshNormal];
		}
        //拉得很下，而且目前的状态不是loading，进行状态改变，改变为loading状态
        else if (_state == PullRefreshNormal && scrollView.contentOffset.y < -65.0f && !_loading)
        {
			[self setState:PullRefreshPulling];
		}
		
		if (scrollView.contentInset.top != 0) {
			scrollView.contentInset = UIEdgeInsetsZero;
		}
		
	}
    
}
- (void)refreshScrollViewDidEndDragging:(UIScrollView *)scrollView
{
    BOOL _loading = NO;
	if ([delegate respondsToSelector:@selector(refreshTableHeaderDataSourceIsLoading:)]) {
		_loading = [delegate refreshTableHeaderDataSourceIsLoading:self];
	}
	
	if (scrollView.contentOffset.y <= - 65.0f && !_loading)
    {
		
		if ([delegate respondsToSelector:@selector(refreshTableHeaderDidTriggerRefresh:)])
        {
			[delegate refreshTableHeaderDidTriggerRefresh:self];
		}
		
		[self setState:PullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
		
	}
}

- (void)refreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView
{

    NSLog(@"数据刷新完毕，tableview弄回原来位置");
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	[self setState:PullRefreshNormal];
   
}


- (void)setState:(PullRefreshState)aState
{
    switch (aState) {
        //下拉状态
		case PullRefreshPulling:
			
			_statusLabel.text =  @"Release to refresh status";
			[CATransaction begin];
			[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
			_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
			[CATransaction commit];
			
			break;
            //正常状态
		case PullRefreshNormal:
			
            if (_state == PullRefreshPulling)
            {
                //之前的状态为下拉状态 debugmark
				[CATransaction begin];
				[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
				_arrowImage.transform = CATransform3DIdentity;
				[CATransaction commit];
			}
			
			_statusLabel.text = @"Pull down to refresh...";
			[_activityView stopAnimating];//停止菊花
            //转箭头
			[CATransaction begin];
			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
			_arrowImage.hidden = NO;
			_arrowImage.transform = CATransform3DIdentity;
			[CATransaction commit];
			
			[self refreshLastUpdatedDate];
			
			break;
		case PullRefreshLoading:
			
			_statusLabel.text = @"Loading Status";
			[_activityView startAnimating];
			[CATransaction begin];
			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
			_arrowImage.hidden = YES;
			[CATransaction commit];
			
			break;
		default:
			break;
	}
	
	_state = aState;
}

@end
